package com.mark.service.impl;

import com.google.common.collect.Lists;
import com.mark.exception.FTPUtilException;
import com.mark.service.IFileService;
import com.mark.util.FTPUtil;
import com.mark.util.ImageUtil;
import com.mark.util.PathUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传的逻辑
 * Created by Mark on 2018/3/26.
 */
@Service("fileServiceImpl")
@Slf4j
public class FileServiceImpl implements IFileService{

    @Override
    public String upload(MultipartFile file, String path ,String sole,int soleId) {
        String targetAddress = null;
        String fileName = file.getOriginalFilename();
//        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);//获取扩展名
//        String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;//重新命名上传文件
        String uploadFileName = ImageUtil.getNewFileName(fileName);//重新命名上传文件
        //log.info("开始上传文件,上传文件的文件名:{},上传的路径:{},新文件名:{}",fileName,path,uploadFileName);

        File fileDir = new File(path);//声明路径文件夹
        if(!fileDir.exists()){//如果路径文件不存在就自动创建
            fileDir.setWritable(true);//赋予可写权限
            fileDir.mkdirs();
        }
        File targetFile = new File(path,uploadFileName);//声明一个文件
        try {
            file.transferTo(targetFile);//SpringMVC封装的file转换为targetFile，此时文件已经上传成功了到本地文件夹
            ImageUtil.generateThumbnailUpload(targetFile);
            //Boolean isSuccess =  FTPUtil.uploadFile(Lists.newArrayList(targetFile),"");//将targetFile上传到FTP服务器
            Boolean isSuccess = false;
            if(!isSuccess){
                if(StringUtils.equals("user",sole)){
                    targetAddress = PathUtil.getUserImageath(soleId);
                }else if(StringUtils.equals("product",sole)){
                    targetAddress = PathUtil.getProductImagePath(soleId);
                }else if(StringUtils.equals("category",sole)){
                    targetAddress = PathUtil.getCategoryImagePath();
                }else if(StringUtils.equals("headLine",sole)){
                    targetAddress = PathUtil.getHeadLineImagePath();
                }else if(StringUtils.equals("simditor",sole)){
                    targetAddress = PathUtil.getSimditorImagePath();
                }
                ImageUtil.generateThumbnail(targetFile,targetAddress);//// TODO: 2018/4/13
            }
            targetFile.delete();//已经上传到ftp服务器上,本地删除文件
        } catch (RuntimeException e) {//// TODO: 2018/5/8
            log.error("上传文件异常",e);
            return null;
        } catch (IOException e) {
            log.error("文件上传到本地异常：{}",e.getClass()+e.getMessage());
        }
        return targetAddress+targetFile.getName();
    }
}
